import logging
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.core.handlers.wsgi import WSGIRequest
from django.http import HttpResponse
from .models import UserAccessLog
import requests
import json
from MC.settings import APP_ID
import base64


logger = logging.getLogger("django")


def get_authen(access_token):
    auth_header = {
        "Authorization": "Bearer " + access_token
    }
    authen = requests.get("http://122.152.244.89/check_token", headers=auth_header)
    return json.loads(authen.text)


def get_token(code, raw_url):
    post_header = {
        "Authorization": "Basic " + str(base64.b64encode(bytes(APP_ID, encoding="utf8")), encoding="utf8")
    }
    # print("Basic " + str(base64.b64encode(bytes(APP_ID, encoding="utf8")), encoding="utf8"))
    post_args = {
        "grant_type": "authorization_code",
        "code": code,
        # "redirect_uri": "http://10.167.193.94" + raw_url.split("?")[0]
        "redirect_uri": "http://mc" + raw_url.split("?")[0]
    }
    token = requests.post("http://122.152.244.89/oauth/token?",
                              data=post_args, headers=post_header)
    return json.loads(token.text)


def return_respons(request, args_, access_token, view_func):
    auth = get_authen(access_token)
    raw_url = request.get_full_path()
    # args = "http://mc" + raw_url.split("?")[0]
    args = "response_type=code&client_id=beacon&redirect_uri=http://mc" + raw_url.split("?")[0]

    request.session["access_token"] = access_token
    request.session.set_expiry(0)
    try:
        if auth["payload"]["user_name"]:

            raw_url = request.get_full_path()
            if request.META.get('HTTP_X_FORWARDED_FOR'):
                ip = request.META['HTTP_X_FORWARDED_FOR']
            else:
                ip = request.META['REMOTE_ADDR']
            # try:
            # 用戶訪問日誌
            user_log = UserAccessLog()
            user_log.access_url = raw_url.split("?")[0]
            user_log.access_ip = ip
            user_log.user = auth["payload"]["user_name"]
            user_log.company_id = auth["payload"]["f_account"]
            user_log.save()

            return view_func(request, args_, auth)
    except:
        # return redirect("http://122.152.244.89:9301/oauth/authorize?" + args)

        return redirect("http://122.152.244.89/oauth/authorize?" + args)


def login_authen(view_func):

    def authen(request, *args_):
        raw_url = request.get_full_path()
        if "access_token" in request.session:
            access_token = request.session["access_token"]

        elif request.GET.get("code"):
            code = request.GET.get("code")
            token_data = get_token(code, raw_url)
            access_token = token_data["access_token"]

        else:
            args = "response_type=code&client_id=beacon&redirect_uri=http://mc" + raw_url.split("?")[0]
            return redirect("http://122.152.244.89/oauth/authorize?" + args)
        return return_respons(request, args_, access_token, view_func)

    return authen


@login_authen
def test(request, args, auth):
    response = HttpResponse(auth)
    print("hahaha")
    return HttpResponse("認證登陸成功!")


@login_authen
def test2(request, args, auth):
    print(auth)
    raw_url = request.get_full_path()
    if request.META.get('HTTP_X_FORWARDED_FOR'):
        ip = request.META['HTTP_X_FORWARDED_FOR']
    else:
        ip = request.META['REMOTE_ADDR']

    return HttpResponse("ok")


